//
//  QiguaViewController.m
//  Fengshui
//
//  Created by are on 13-5-22.
//
//

#import "QiguaViewController.h"
#import "SGResultViewController.h"

@interface QiguaViewController ()

@end

@implementation QiguaViewController
@synthesize typeString = _typeString;
@synthesize kindButtonArray = _kindButtonArray;
@synthesize wupinImageResourceArray = _wupinImageResourceArray;
@synthesize FirstElement;
@synthesize SecondElement;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)timeLabel
{
    NSDateFormatter *formatter =[[[NSDateFormatter alloc] init] autorelease];
    NSDate *date = [NSDate date];
    [[NSDate date] timeIntervalSince1970];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    [(UILabel *)[self.selectTimeView viewWithTag:1] setText:[formatter stringFromDate:date]];
}
#pragma viewAction
-(void)viewWillAppear:(BOOL)animated
{
    
    NSString *string = [[NSBundle mainBundle] pathForResource:@"baguawupin" ofType:@"bundle"];
    NSArray *jpgArray = [NSBundle pathsForResourcesOfType:@"jpg" inDirectory:string];
    NSArray *pngArray = [NSBundle pathsForResourcesOfType:@"png" inDirectory:string];
    NSArray *JPGArray = [NSBundle pathsForResourcesOfType:@"JPG" inDirectory:string];
    NSMutableArray *m_array = [NSMutableArray arrayWithArray:jpgArray];
    [m_array addObjectsFromArray:JPGArray];
    [m_array addObjectsFromArray:pngArray];
    
    self.refreshTimer =[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeLabel) userInfo:nil repeats:YES];
    for (NSInteger i = m_array.count-1; i > 0; i--)
        
    {
        [m_array exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform(i+1)];
        Dlog(@"%@",[m_array objectAtIndex:i]);
    }
    
    self.wupinImageResourceArray = [NSArray arrayWithArray:m_array];
    keyBoardController=[[UIKeyboardViewController alloc] initWithControllerDelegate:self.selectNumberView];
    
    [keyBoardController addToolbarToKeyboard];
    
    [super viewWillAppear:animated];
}
-(void)viewDidDisappear:(BOOL)animated
{
    
    keyBoardController.boardDelegate = nil;
    [keyBoardController release];
    
    [super viewDidDisappear:animated];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [self.refreshTimer invalidate];
    self.refreshTimer = nil;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.kindButtonArray = [NSMutableArray array];
    NSArray *array = [NSArray arrayWithObjects:@"时间起卦",@"穿衣服的颜色起卦",@"选物品起卦",@"输入数字起卦",nil];

    for (NSInteger i = 0; i<[array count]; i++) {
        QiguaChoosingKindView *view =  [[[NSBundle mainBundle] loadNibNamed:@"QiguaChoosingKindView" owner:self options:nil] objectAtIndex:0];
        [(UILabel *)[view viewWithTag:2] setText:[NSString stringWithFormat:@"%@",[array objectAtIndex:i]]];
        view.delegate = self;
        [view setFrame:CGRectMake(80, 50+i*(30+37), 220, 37)];
        [self.view addSubview:view];
        [self.kindButtonArray addObject:view];
    }
    // Do any additional setup after loading the view from its nib.
}
#pragma -----------

#pragma kindView-delegate
-(void)controlSelected:(QiguaChoosingKindView*)view
{
    NSInteger selectedNum ;
    for (NSInteger i = 0; i<[self.kindButtonArray count]; i++) {

        QiguaChoosingKindView * m_view = [self.kindButtonArray objectAtIndex:i];
        if (view == m_view) {
           
            [(UIImageView *)[view viewWithTag:1] setImage:[UIImage imageNamed:@"choosed.png"]];
            selectedNum = i;
        }
        else
        {
            [(UIImageView *)[m_view viewWithTag:1] setImage:[UIImage imageNamed:@"choose.png"]];
        }

    }
    UIView *selectedView;
    switch (selectedNum) {
        case 0:
            selectedView = self.selectTimeView;
            break;
        case 1:
            selectedView = self.selectColorView;
            break;
        case 2:
            selectedView = self.selectArticleView;
            break;
        case 3:
            selectedView = self.selectNumberView;

            break;
    }
    
    if([[self.view subviews] containsObject:selectedView]){
        
        [selectedView removeFromSuperview];
    }
    
    [self.view addSubview:selectedView];
    [selectedView setFrame:CGRectMake(320, 0, 320, selectedView.frame.size.height)];
    [UIView animateWithDuration:0.3f animations:^(void){
        [selectedView setFrame:CGRectMake(0, 0, 320, selectedView.frame.size.height)];
    }];    
    
}
#pragma ---------

#pragma btnAction
-(IBAction)lastStepBeforeBeginSuanGua:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    if (button.superview == self.selectNumberView) {

        [keyBoardController resignKeyboard:self.selectNumberView];

    }
    [button.superview setFrame:CGRectMake(0, 0, 320, button.superview.frame.size.height)];
    [UIView animateWithDuration:0.3f animations:^(void){
        [button.superview setFrame:CGRectMake(320, 0, 320, button.superview.frame.size.height)];
    }];
}
-(IBAction)colorBtnAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    UILabel *label1 = (UILabel *)[self.selectColorView viewWithTag:11];
    UILabel *label2 = (UILabel *)[self.selectColorView viewWithTag:22];
    if (![label1.text isEqualToString:@""]&&![label2.text isEqualToString:@""]) {

        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"已经选择完成!"
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
    if ([label1.text isEqualToString:@""]) {

        label1.text = button.titleLabel.text;
        FirstElement = button.tag;
        return;
        
    }
    if ([label2.text isEqualToString:@""]) {

        label2.text = button.titleLabel.text;
        SecondElement = button.tag;
        return;
    }
    
}
-(IBAction)lastStep:(id)sender
{
    
    UIButton *button = (UIButton *)sender;
    UILabel *label1 = (UILabel *)[self.selectColorView viewWithTag:11];
    UILabel *label2 = (UILabel *)[self.selectColorView viewWithTag:22];
    label1.text = @"";
    label2.text = @"";

    UITextField *textField1 = (UITextField *)[self.selectNumberView viewWithTag:1];
    UITextField *textField2 = (UITextField *)[self.selectNumberView viewWithTag:2];
    textField1.text = @"";
    textField2.text = @"";

    UIImageView *imageView1 = (UIImageView *)[self.selectArticleView viewWithTag:1];
    UIImageView *imageView2 = (UIImageView *)[self.selectArticleView viewWithTag:2];
    imageView1.image = nil;
    imageView2.image = nil;

    if (button.superview == self.selectNumberView) {

        [keyBoardController resignKeyboard:self.selectNumberView];
        
    }
    [button.superview setFrame:CGRectMake(0, 0, 320, button.superview.frame.size.height)];
    [UIView animateWithDuration:0.3f animations:^(void){
        [button.superview setFrame:CGRectMake(320, 0, 320, button.superview.frame.size.height)];
    }];
    //[button.superview removeFromSuperview];
    
}
-(IBAction)nextStep:(id)sender
{
    UIButton *button = (UIButton *)sender;
    if (button.superview == self.selectNumberView) {

        [keyBoardController resignKeyboard:self.selectNumberView];
        UITextField *textField1 = (UITextField *)[self.selectNumberView viewWithTag:1];
        UITextField *textField2 = (UITextField *)[self.selectNumberView viewWithTag:2];
        if ([textField1.text isEqualToString:@""]||[textField2.text isEqualToString:@""]) {

            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                message:@"起卦条件不完整!"
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
            [alertView show];
            [alertView release];
            return;
            
        }
        else
        {
            FirstElement = [textField1.text intValue];
            SecondElement = [textField2.text intValue];
        }
    }
    if (button.superview == self.selectColorView)
    {
        UILabel *label1 = (UILabel *)[self.selectColorView viewWithTag:11];
        UILabel *label2 = (UILabel *)[self.selectColorView viewWithTag:22];
        if ([label1.text isEqualToString:@""]||[label2.text isEqualToString:@""]) {

            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                message:@"起卦条件不完整!"
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
            [alertView show];
            [alertView release];
            return;
            
        }
    }
    if (button.superview == self.selectArticleView) {

        UIImageView *imageView1 = (UIImageView *)[self.selectArticleView viewWithTag:1];
        UIImageView *imageView2 = (UIImageView *)[self.selectArticleView viewWithTag:2];

        if (!imageView1.image||!imageView2.image) {
            
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                message:@"起卦条件不完整!"
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
            [alertView show];
            [alertView release];
            return;

        }

    }
    if (button.superview == self.selectTimeView) {

        NSString *string = [(UILabel *)[self.selectTimeView viewWithTag:1] text];
        NSArray *array = [string componentsSeparatedByString:@":"];
        FirstElement = [[array objectAtIndex:0] intValue];
        SecondElement = [[array objectAtIndex:1] intValue];
        

    }
     
    if([[self.view subviews] containsObject:self.jingxinMovieView]){

        [self.jingxinMovieView removeFromSuperview];
    }
    
    [self.view addSubview:self.jingxinMovieView];
    [self.jingxinMovieView setFrame:CGRectMake(320, 0, 320, self.jingxinMovieView.frame.size.height)];
    [UIView animateWithDuration:0.3f animations:^(void){
        [self.jingxinMovieView setFrame:CGRectMake(0, 0, 320, self.jingxinMovieView.frame.size.height)];
    }];
    
}
-(IBAction)beginSuanGua:(id)sender
{
    char *qiGuaResult = qiGua(FirstElement, SecondElement);

    NSString *resultString = [NSString stringWithUTF8String:qiGuaResult];
    NSArray *resultArray = [resultString JSONValue];
    SGResultViewController *resultViewController = [[SGResultViewController alloc] initWithNibName:@"SGResultViewController" bundle:nil];
    
    [resultViewController setDataArray:resultArray];
    [self.navigationController pushViewController:resultViewController animated:YES];
    [resultViewController release];
}
#pragma tableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return ceil((float)self.wupinImageResourceArray.count / 3);;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *string = @"cell";
    LocalPhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"LocalPhotoCell" owner:self options:nil] objectAtIndex:0];
    }
    NSUInteger firstPhotoInCell = indexPath.row * 3;
    NSUInteger lastPhotoInCell  = firstPhotoInCell + 3;

    if (self.wupinImageResourceArray.count <= firstPhotoInCell) {
        return nil;
    }

    NSUInteger currentPhotoIndex = 0;
    NSUInteger lastPhotoIndex = MIN(lastPhotoInCell, self.wupinImageResourceArray.count);
    for ( ; firstPhotoInCell + currentPhotoIndex < lastPhotoIndex ; currentPhotoIndex++) {
        UIImage *image = [UIImage imageWithContentsOfFile:[self.wupinImageResourceArray objectAtIndex:firstPhotoInCell + currentPhotoIndex]];
        
        switch (currentPhotoIndex) {
            case 0:
                cell.photo1.hidden = NO;
                [cell.photo1 setImage:image];

                break;
            case 1:
                cell.photo2.hidden = NO;
                [cell.photo2 setImage:image];

                break;
            case 2:
                cell.photo3.hidden = NO;
                [cell.photo3 setImage:image];
                
                break;
            default:
                break;
        }
    }
    cell.rowNumber = indexPath.row;
    cell.selectionDelegate = self;
    return cell;

}
#pragma ------cellDelegate
- (void)albumContentsTableViewCell:(LocalPhotoCell *)cell selectedPhotoAtIndex:(NSUInteger)index
{
    UIImageView *imageView1 = (UIImageView *)[self.selectArticleView viewWithTag:1];
    UIImageView *imageView2 = (UIImageView *)[self.selectArticleView viewWithTag:2];
    if (imageView1.image &&imageView2.image) {

        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"已经选择完成!"
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
    if (!imageView1.image) {

        NSString *pathString = [self.wupinImageResourceArray objectAtIndex:(cell.rowNumber * 3) + index];
        imageView1.image = [UIImage imageWithContentsOfFile:pathString];
        NSArray *array = [pathString componentsSeparatedByString:@"/"];
        NSString *numberString = [[[array lastObject] componentsSeparatedByString:@"_"] objectAtIndex:0];
        FirstElement = [numberString intValue];
        Dlog(@"%@",numberString);
        return;
    }
    if (!imageView2.image) {

        NSString *pathString = [self.wupinImageResourceArray objectAtIndex:(cell.rowNumber * 3) + index];
        imageView2.image = [UIImage imageWithContentsOfFile:pathString];
        NSArray *array = [pathString componentsSeparatedByString:@"/"];
        NSString *numberString = [[[array lastObject] componentsSeparatedByString:@"_"] objectAtIndex:0];
        SecondElement = [numberString intValue];
        
        return;
    }
}

@end



